package com.xiangxiao.rpan.authority.oauth;

import com.google.gson.Gson;
import com.xiangxiao.rpan.authority.constant.ResponseCode;
import com.xiangxiao.rpan.authority.dto.JsonObject;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @auther xiangxiao
 * @email 573768011@qq.com
 * @data 2023/3/21 19:52
 */
/**
 * AuthenticationEntryPoint 接口用于处理在用户尝试访问受保护资源时出现的身份验证异常。
 * 它定义了一个方法 commence，该方法在身份验证失败时被调用，
 * 允许应用程序自定义处理方式，例如重定向到登录页面、返回特定的错误响应等。
 * */
public class LocalAuthenticationEntryPoint implements AuthenticationEntryPoint {
  @Override
  public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
    JsonObject object = new JsonObject();
    object.setRespMessage("没有登录或者token错误");
    object.setRespCode(ResponseCode.NO_LOGIN);
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    Gson gson = new Gson();
    response.setContentType("application/json;charset=utf-8");
    response.getWriter().write(gson.toJson(object));
  }
}
